// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.data.exceptions

import android.content.Context
import androidx.appcompat.content.res.AppCompatResources
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import org.acra.ktx.sendSilentlyWithAcra
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.api.Error
import xyz.apiote.bimba.czwek.data.FeedInfoFlowItem
import xyz.apiote.bimba.czwek.data.ResultFlowItem

abstract class BimbaException(override val message: String?, override val cause: Error) :
	Exception(message, cause), FeedInfoFlowItem, ResultFlowItem {
	abstract fun isReportable(): Boolean

	override fun equals(other: Any?): Boolean {
		if (other !is BimbaException) return false

		return message == other.message && cause == other.cause
	}

	companion object {
		fun showDialog(context: Context, exceptions: List<BimbaException>) {
			val dialogue = MaterialAlertDialogBuilder(context)
				.setIcon(
					AppCompatResources.getDrawable(
						context,
						R.drawable.error_other
					)
				)
				.setTitle(R.string.error)
				.setItems(exceptions.map { "${it.message}: ${it.cause.message ?: ""}\n${context.getString(it.cause.stringResource)}" }
					.toTypedArray(), null)
				.setPositiveButton(R.string.ok) { _, _ -> }

			if (exceptions.any { it.isReportable() }) {
				dialogue.setNeutralButton(R.string.send_a_report) { _, _ ->
					exceptions.filter { it.isReportable() }.forEach { it.sendSilentlyWithAcra() }
				}
			}

			dialogue.show()
		}
	}

	override fun hashCode(): Int {
		var result = message?.hashCode() ?: 0
		result = 31 * result + cause.hashCode()
		return result
	}
}